package com.kcyu.sfherp.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.chain.SheetHandlerExecutionChain;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kcyu.sfherp.config.TimestampConverter;
import com.kcyu.sfherp.dto.ExportChmxDTO;
import com.kcyu.sfherp.entity.Chmx;
import com.kcyu.sfherp.entity.Custom;
import com.kcyu.sfherp.entity.utilEntity.ExcelChmx;
import com.kcyu.sfherp.mapper.ms.CustomMapper;
import com.kcyu.sfherp.service.ChzdService;
import com.kcyu.sfherp.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {

    @Autowired
    private ChzdService chzdService;

    @Autowired
    private CustomMapper customMapper;

    @PostMapping("/queryDebtByName")
    public Map<Object,Object> queryDebtByName(@RequestBody Map info){
        String customer = (String) info.get("customer");
        String startTime = (String) info.get("startTime");
        String endTime = (String) info.get("endTime");
        HashMap<Object, Object> map = new HashMap<>();
        return map;
    }

    @PostMapping("/queryDZMX")
    public ResponseResult<List<Chmx>> queryDZMX(@RequestBody ExportChmxDTO dto){
        List<Chmx> chmxes = chzdService.queryChmx(dto.getKhname(), dto.getStartTime(), dto.getEndTime());
        return new ResponseResult<>(200, chmxes);
    }

    @PostMapping("/exportChmx")
    public void exportChmx(HttpServletResponse response, @RequestBody ExportChmxDTO dto) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName1 = dto.getKhname() + "对账单";
        String fileName = URLEncoder.encode(fileName1, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        WriteCellStyle headStyle = GoodController.rewriteCellStyle();


        List<Chmx> chmxes = chzdService.queryChmx(dto.getKhname(), dto.getStartTime(), dto.getEndTime());
        log.info("明细列表: {}", chmxes);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        log.info("申请导出Excel，客户:{}", dto.getKhname());

        List<ExcelChmx> excelChmxes = new ArrayList<>();
        for(Chmx chmx1: chmxes) {
            ExcelChmx excelChmx = new ExcelChmx();
            excelChmx.setDh(chmx1.getDh());
            excelChmx.setSpname(chmx1.getSpname());
            excelChmx.setSl(chmx1.getSl());
            excelChmx.setRq(chmx1.getRq());
            excelChmx.setJg(chmx1.getJg());
            excelChmx.setDw(chmx1.getDw());
            excelChmx.setKhname(chmx1.getKhname());
            WriteCellData<Number> cellData = new WriteCellData<Number>();
            cellData.setType(CellDataTypeEnum.NUMBER);
            cellData.setNumberValue(new BigDecimal(chmx1.getJe()));
            excelChmx.setJe(cellData);
            excelChmxes.add(excelChmx);
        }
        
        // 增加结尾的统计行
        excelChmxes.add(new ExcelChmx());
        ExcelChmx countLine = new ExcelChmx();
        countLine.setSpname("合计");
        WriteCellData<Number> cellData = new WriteCellData<Number>();
        countLine.setJe(cellData);
        FormulaData formulaData = new FormulaData();
        cellData.setFormulaData(formulaData);
        formulaData.setFormulaValue("SUM(F2:F" + (excelChmxes.size() + 1) + ")");
        excelChmxes.add(countLine);

        EasyExcel
                .write(response.getOutputStream(), ExcelChmx.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, headStyle))
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerConverter(new TimestampConverter())
                .sheet("sheet1")
                .doWrite(excelChmxes);
    }

    @PostMapping("/getAllCustomer")
    public ResponseResult<List<Custom>> getAllCustomer() {
        QueryWrapper<Custom> wrapper = new QueryWrapper<>();
        List<Custom> customs = customMapper.selectList(wrapper);
        return new ResponseResult<>(200, customs);
    }
}
